package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VoiceApiImpl implements VoiceApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Long seelctCount(Long userId, String format) {
        Criteria createDate = Criteria.where("creatDate").is(format).and("userId").is(userId);
        Query query = new Query(createDate);
        long count = mongoTemplate.count(query, Voice.class);

        return count;
    }

    //表内添加数据
    @Override
    public Boolean save(Voice voice) {
        if (voice== null){
            return false;
        }
        mongoTemplate.save(voice);
        return true;
    }

    //随机查询一天userid不为用户自身的数据
    @Override
    public Voice selectRandom(Long userId1) {
        Criteria criteria = Criteria.where("userId").nin(userId1).and("isListen").is(true);
        long count = mongoTemplate.count(Query.query(criteria),Voice.class);
        //1、创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Voice.class,Aggregation.match(criteria),Aggregation.sample(1));
        //2、调用mongoTemplate方法统计
        AggregationResults<Voice> results = mongoTemplate.aggregate(aggregation, Voice.class);

        List<Voice> mappedResults = results.getMappedResults();

        if (mappedResults.size()==0){
            if (count==0){
                return null;
            }
            Voice voice = selectRandom(userId1);
            mappedResults.add(voice);

        }
        Voice voice = mappedResults.get(0);
        //将修改后的Voice存入数据库，覆盖原本的数据

        voice.setIsListen(false);
        mongoTemplate.save(voice);
        return voice;
    }
}
